package com.kun.lagou.user.controller;

import com.alibaba.fastjson.JSON;
import com.kun.lagou.user.api.dto.UserInfo;
import com.kun.lagou.user.model.User;
import com.kun.lagou.user.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author Administrator
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class UserController {
    private static final String SECRETKEY = "aldjflaksdjf";//一般不写在代码里
    private static final String COOKIE_NAME = "my-jwt";
    private final UserService userService;

    @PostMapping("/login")
    public UserInfo login(@RequestParam("phoneNumber") String phoneNumber,
                          @RequestParam("code") String code,
                          HttpServletResponse response) {
        User user = userService.login(phoneNumber, code);
        var jwt = Jwts.builder()
                .setSubject(JSON.toJSONString(user))
                .claim("phoneNumber", user.getPhoneNumber())
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, SECRETKEY).compact();
        response.addCookie(new Cookie(COOKIE_NAME, jwt));
        return UserInfo.builder()
                .id(user.getId())
                .nickname(user.getNickname())
                .phoneNumber(user.getPhoneNumber())
                .build();
    }









}
